package com.kaifamiao.kfm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kaifamiao.kfm.entity.SysRole;
import com.kaifamiao.kfm.entity.SysUser;
import com.kaifamiao.kfm.entity.TreeMenuDTO;
import com.kaifamiao.kfm.service.SysRoleService;
import com.kaifamiao.kfm.service.SysUserService;
import com.kaifamiao.kfm.util.Constants;
import com.kaifamiao.kfm.util.JsonResult;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping({"/login", "/"})
    public ModelAndView toLogin() {
        return new ModelAndView("login.html");
    }

    @GetMapping("/verificationCode")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // png类型
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);
        System.out.println(captcha.text());  // 获取验证码的字符
        // 验证码存 redis
        redisTemplate.opsForValue().set(request.getSession().getId() + Constants.CAPTCHA_KEY_SUFF, captcha.text(), Constants.TIMEOUT, TimeUnit.MINUTES);
        captcha.out(response.getOutputStream());
    }

    @PostMapping("/login")
    public JsonResult doLogin(String username, String password, String code, HttpSession session){
        String captcha = (String) redisTemplate.opsForValue().get(session.getId() + Constants.CAPTCHA_KEY_SUFF);

        if (code != null && code.equalsIgnoreCase(captcha)){
            redisTemplate.delete(session.getId() + Constants.CAPTCHA_KEY_SUFF);
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("email", username);
            wrapper.eq("password", password);
            SysUser user = sysUserService.getOne(wrapper);
            if (user != null){
                redisTemplate.opsForValue().set(session.getId() + Constants.LOGIN_USER_KEY_SUFF, user);
                session.setAttribute("user", user);

                return JsonResult.success("登录成功", "/index");
            } else{
                return JsonResult.error("用户名或密码错误");
            }
        } else{
            return JsonResult.error( "验证码错误");
        }
    }

    @GetMapping("/index")
    @PreAuthorize("hasRole('ROLE_admin')")
    public ModelAndView index(HttpSession session){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SysUser user = (SysUser) authentication.getPrincipal();
        Collection<TreeMenuDTO> menus = sysUserService.getMenus(user);
        session.setAttribute("menus", menus);
        return new ModelAndView("index.html");
    }

    @GetMapping("/echarts")
    public ModelAndView echarts(){
        return new ModelAndView("echarts.html");
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session){
        redisTemplate.delete(session.getId() + Constants.LOGIN_USER_KEY_SUFF);
        session.invalidate();
        return new ModelAndView("login.html");
    }
}
